package mqttLib

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"math/rand"
	"strconv"
)

type MqttConfig struct {
	Broker string
	ClientID string
}
// topic
const (
	Setting = "/setting"
	Binding = "/binding"
	Unbinding = "/unbinding"
	RealTimeData = "/realtimedata"
	DeviceOnline = "device/online"
	DeviceOffline = "device/offline"
	MqttServer = "tcp://dcharles.work:1883"
)
var DefaultMqttconfig = MqttConfig{
	Broker:     MqttServer,
	ClientID: "history-data-client" + strconv.Itoa(rand.Intn(10000)),
}

func NewMqttClient(mc MqttConfig, onMsgHandler func(client mqtt.Client, msg mqtt.Message)) mqtt.Client{
	clientOption := mqtt.NewClientOptions().AddBroker(mc.Broker).SetClientID(mc.ClientID)
	//clientOption.OnConnect = onMqttConnect
	clientOption.SetDefaultPublishHandler(onMsgHandler)
	client := mqtt.NewClient(clientOption)
	return client
}

func onMqttConnect(c mqtt.Client) {
	fmt.Println("mqtt connected")
}